import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_mode/utils.dart';
import 'package:flutter_mode/zyj/ui/webview.dart';
import 'package:json_annotation/json_annotation.dart';

part 'json_demo.g.dart';

@JsonSerializable()
class _Book {
  String name;
  _Author? author;
  String birth;

  @override
  String toString() {
    return '_Book{name: $name, author: $author, birth: $birth}';
  }

  _Book(this.name, this.author, this.birth);

  factory _Book.fromJson(Map<String, dynamic> json) => _$_BookFromJson(json);
}

@JsonSerializable()
class _Author {
  String name;
  int age;

  @override
  String toString() {
    return '_Author{name: $name, age: $age}';
  }

  _Author(this.name, this.age);

  factory _Author.fromJson(Map<String, dynamic> json) =>
      _$_AuthorFromJson(json);
}

class JsonDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    var items = {
      'Json解析': () {
        String jsData =
            '[{"name":"Kivo", "age": 7}, {"name":"Konio", "age": 17}]';
        List<dynamic> jd = json.decode(jsData);
        Map<String, dynamic> ud = jd[0];

        print(jd[0]);
        print(ud['name']);
      },
      '构造Json': () {
        var js = json.encode([
          {"name": "Kivo", "age": 7},
          {"name": "Konio", "age": 17}
        ]);
        print(js);
      },
      '': () {},
      '对象 -> Json': () {
        var author = _Author('Davin', 19);
        var book = _Book('Who are you?', author, '2017-02-18');
        print(_$_BookToJson(book));
      },
      'Json -> 对象': () {
        String jsData =
            '{"name":"How are you!", "birth":"2017-05-28", "author":{"name":"Kinoe", "age": 12}}';
        print(_Book.fromJson(json.decode(jsData)));
      },
      ' ': () {},
      'doc: https://www.jianshu.com/p/3754d1370ccc': () => pushMaterial(
          context,
          WebViewPage(
            title: 'doc',
            url: 'https://www.jianshu.com/p/3754d1370ccc',
          )),
      '感觉不好用，有时间看能不能自己写个idea插件。或者使用http://json2dart.com/ 创建json对象': () =>
          pushMaterial(
              context,
              WebViewPage(
                title: 'doc',
                url: 'http://json2dart.com',
              )),
    };

    return Scaffold(
      appBar: AppBar(
        title: Text('JsonDemo'),
      ),
      body: ListView.separated(
        itemBuilder: (context, position) {
          var item = items.entries.elementAt(position);
          return ListTile(
            title: Text(item.key),
            onTap: item.value,
          );
        },
        itemCount: items.length,
        separatorBuilder: (context, position) => Divider(
              height: 1,
            ),
      ),
    );
  }
}
